package com.roc.admin.interfaces.controller.auth;

import cn.dev33.satoken.stp.StpUtil;
import com.roc.admin.application.service.UserService;
import com.roc.admin.domain.entity.User;
import com.roc.admin.interfaces.common.Result;
import com.roc.admin.interfaces.dto.UserDTO;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.AllArgsConstructor;
import org.springframework.web.bind.annotation.*;

/**
 * 用户控制器
 */
@Tag(name = "授权管理", description = "授权管理相关接口")
@RestController
@RequestMapping("/auth")
@AllArgsConstructor
public class AuthController {
    private final UserService userService;

    @Operation(summary = "用户登录")
    @PostMapping("/login")
    public Result<UserDTO> login(@Parameter(description = "用户名") @RequestParam String username,
                                @Parameter(description = "密码") @RequestParam String password) {
        User user = userService.login(username, password);
        if (user == null) {
            return Result.failed("用户名或密码错误");
        }
        
        // 使用Sa-Token登录
        StpUtil.login(user.getId());
        
        UserDTO userDTO = userService.getUserByUsername(username);
        return Result.success(userDTO);
    }
    
    @Operation(summary = "用户登出")
    @PostMapping("/logout")
    public Result<String> logout() {
        StpUtil.logout();
        return Result.success("登出成功");
    }
    
    @Operation(summary = "获取当前登录用户信息")
    @GetMapping("/info")
    public Result<UserDTO> getCurrentUserInfo() {
        // 获取当前登录用户ID
        Long userId = StpUtil.getLoginIdAsLong();
        UserDTO userDTO = userService.getUserById(userId);
        return Result.success(userDTO);
    }
    
    @Operation(summary = "检查用户是否登录")
    @GetMapping("/isLogin")
    public Result<Boolean> isLogin() {
        return Result.success(StpUtil.isLogin());
    }
}
